package com.pactera.asmp.server.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;

public class CsvUtils {

    private static Logger logger = LoggerFactory.getLogger(CsvUtils.class);

    /**
     * 读取CSV
     * 
     * @param filePath
     * @param fields
     * @return
     * @throws IOException
     */
    public static List<List<String>> read(MultipartFile file) {
        List<List<String>> resultList = Lists.newArrayList();
        int i = 0;
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8.name());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            CSVReader csvReader = new CSVReaderBuilder(bufferedReader).build();
            Iterator<String[]> iterator = csvReader.iterator();
            while (iterator.hasNext()) {
                String[] next = iterator.next();
                if (i == 0) {
                    i++;
                    continue;
                }
                resultList.add(Lists.newArrayList(next));
                i++;
            }
            return resultList;
        } catch (Exception ex) {
            logger.error("read csv error, {}", ex.getMessage());
            return null;
        }
    }

}
